package com.eimf.saf.base.filter;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eimf.saf.security.entity.Staff;

/**
 * @author eden
 * @date 2013-11-13 下午2:32:27
 * @Description: 所有请求必须经过session过滤，避免非法请求
 */
public class SessionFilter implements Filter
{

    private final Set<String> execludeSet = new HashSet<String>();

    private static Log logger = LogFactory.getLog(SessionFilter.class);

    @Override
    public void init(final FilterConfig config) throws ServletException
    {
        final String excludes = config.getInitParameter("exclude");
        if (excludes == null)
        {
            return;
        }
        final StringTokenizer st = new StringTokenizer(excludes, ",");
        while (st.hasMoreTokens())
        {
            this.execludeSet.add(st.nextToken());
        }
    }

    @Override
    public void destroy()
    {
        this.execludeSet.clear();
    }

    /**
     * 检查是否请求是否合法
     */
    @Override
    public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
            throws IOException, ServletException
    {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) resp;
        if (!this.execludeSet.contains(request.getServletPath()))
        {
            final long start = System.currentTimeMillis();

            final HttpSession session = request.getSession();
            final Staff staff = (Staff) session.getAttribute("staff");
            if ((staff == null) || (staff.getLoginName() == null))
            {
                redirectLogin(request, response);
                return;
            }
            SessionFilter.logger.debug("SessionFilter(" + request.getServletPath() + ") used:"
                    + (System.currentTimeMillis() - start));
        }
        chain.doFilter(req, resp);
    }

    /**
     * redirectLogin(重新定位登录页面)
     * 
     * @param request
     * @param response
     * @throws IOException void
     * @exception
     * @since 1.0.0
     */
    private void redirectLogin(final HttpServletRequest request, final HttpServletResponse response) throws IOException
    {
        String url = request.getContextPath() + "/index.jsp";

        final String redirectURL = request.getServletPath();
        url = url + "?redirectURL=" + URLEncoder.encode(redirectURL) + "&subSystemId=SAF";

        if (null != request.getQueryString())
        {
            url = url + "&" + request.getQueryString();
        }

        final String targetURL = response.encodeRedirectURL(url);
        response.sendRedirect(targetURL);
    }
}
